"""
    Author:
    Date: 2018-12-13

    辅助函数。
"""

from django.conf import settings
from django.shortcuts import render

from utils import wx_util

# WX登录的存根
SESSION_KEY_FOR_WX_LOGIN = '_wx_openid'


def build_context(request):
    """ 构造上下文信息 """
    if not request:
        return {}

    context = {
        'user': request.user,
    }

    if settings.ENV_NAME.upper() == 'PROD':
        env = {
            'name': '(生产环境)',
            'favicon': 'favicon.png',
            'bg': 'hb-bg-prod',
        }
    elif settings.ENV_NAME.upper() == 'TEST':
        env = {
            'name': '(测试环境)',
            'favicon': 'favicon-t.png',
            'bg': 'hb-bg-test'
        }
    elif settings.ENV_NAME.upper() == 'DEV':
        env = {
            'name': '(开发环境)',
            'favicon': 'favicon-d.png',
            'bg': 'hb-bg-dev'
        }
    else:
        env = {
            'name': '(未配置!!)',
            'bg': 'hb-bg-dev'
        }
    context['env'] = env

    return context


def get_request_openid(request):
    """ 获取request对应的openid """
    openid = request.session.get(SESSION_KEY_FOR_WX_LOGIN, None)
    if openid is not None:
        return openid

    if settings.DEBUG:
        return settings.TEST_OPEN_ID

    openid = wx_util.wx_get_web_request_openid(request)
    if openid is not None:
        request.session[SESSION_KEY_FOR_WX_LOGIN] = openid
    return openid


def show_page_500(request, data=None):
    """ 显示500页面 """
    if type(data) == dict:
        message_id = data['id']
        message = data['message']
        message = f'[{message_id}] {message}'
    else:
        message = data
    return render(request, 'mp/500.html', {'message': message})


def show_page_tips(request, data):
    """ 显示提示页面 """
    if type(data) == dict:
        message_id = data['id']
        message = data['message']
        message = f'[{message_id}] {message}'
    else:
        message = data
    return render(request, 'mp/tips.html', {'message': message})


def show_success_page(request, message, redirect_url=''):
    """ 显示成功页面 """
    context = {
        'message': message,
        'redirect_url': redirect_url,
    }
    return render(request, 'mp/success.html', context)


def show_warn_page(request, message, redirect_url=''):
    """ 显示警告页面 """
    context = {
        'message': message,
        'redirect_url': redirect_url,
    }
    return render(request, 'mp/warn.html', context)


# ------------------------------------------------------------------------------
if __name__ == '__main__':
    print('ok')
